package com.summer.ioc.bean.definition.component;

import com.summer.ioc.bean.annotation.Autowired;
import com.summer.ioc.bean.definition.AbstractBeanDefinition;
import com.summer.ioc.exception.BeanException;
import com.summer.ioc.reflect.Parameter;
import com.summer.ioc.util.AnnotationUtil;
import com.summer.ioc.util.MethodUtil;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

/**
 * @author xiaoye
 * @create 2021-05-12 23:38
 */
public class AbstractComponentBeanDefinition extends AbstractBeanDefinition {

    public AbstractComponentBeanDefinition(String name, Class beanClass) {
        super(name, beanClass);
    }

    @Override
    public Set<String> getDependencyBeanNames() {
        if (dependencyBeanNames != null)
            return dependencyBeanNames;

        dependencyBeanNames = new HashSet<>();
        Field[] declaredFields = beanClass.getDeclaredFields();
        for (Field field : declaredFields) {
            if (AnnotationUtil.existAnnotation(field, Autowired.class))
                dependencyBeanNames.add(field.getName());
        }
        Constructor[] constructors = beanClass.getConstructors();
        if (constructors.length > 1)
            throw new BeanException("["+beanClass.getName()+"] 的构造器数量多于1");
        var constructor = constructors[0];
        var parameters = MethodUtil.getParameters(constructor);
        if (AnnotationUtil.existAnnotation(constructor, Autowired.class))
        {
            for (Parameter parameter : parameters) {
                dependencyBeanNames.add(parameter.getName());
            }
        }
        else
        {
            for (Parameter parameter : parameters) {
                if (AnnotationUtil.existAnnotation(parameter.getParameter(),Autowired.class))
                    dependencyBeanNames.add(parameter.getName());
            }
        }
        return dependencyBeanNames;
    }
}
